<?php
namespace Wintel\RestBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class VoiceController
 * @package Wintel\RestBundle\Controller
 */
class VoiceController extends Controller
{
    /**
     * @param Request $request
     * @return JsonResponse
     * 获取留言
     */
    public function listAction(Request $request)
    {
        $vcc_code = $request->get("vcc_code", 0);
        $info = $request->get('info', ''); //分页搜索相关信息；
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
//        $win_ip = $this->container->getParameter('win_ip');
//        $win_web_port = $this->container->getParameter('win_web_port');
//        $win_system_name = $this->container->getParameter('win_system_name');

        $msg = $vcc_id = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message' => 'info格式非json'));
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //主叫号码；
            $where .= isset($addInfo['filter']['caller']) && !empty($addInfo['filter']['caller']) ?
                " AND caller LIKE '%" . $addInfo['filter']['caller'] . "%' " : '';

            //被叫号码
            $where .= isset($addInfo['filter']['called']) && !empty($addInfo['filter']['called']) ?
                " AND called LIKE '%" . $addInfo['filter']['called'] . "%' " : '';

            //是否已收听
            if (isset($addInfo['filter']['listen_mark']) && $addInfo['filter']['listen_mark'] !== false) {
                $listen_mark = $addInfo['filter']['listen_mark'];
                $where .= " AND listen_mark = :listen_mark ";
                $params['listen_mark'] = $listen_mark;
            }

            //是否已下载
            if (isset($addInfo['filter']['down_mark']) && $addInfo['filter']['down_mark'] !== false) {
                $down_mark = $addInfo['filter']['down_mark'];
                $where .= " AND down_mark = :down_mark ";
                $params['down_mark'] = $down_mark;
            }

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $start_time = $addInfo['filter']['start_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where .= "AND start_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where .= "AND start_time <= UNIX_TIMESTAMP('$end_time')";
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                $where .= " AND rec_secs >= :ssecs ";
                $params['ssecs'] = $addInfo['filter']['ssecs'];
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $where .= " AND rec_secs <= :esecs ";
                $params['esecs'] = $addInfo['filter']['esecs'];
            }
        }

        $params['vcc_id'] = $vcc_id;
        $count = $conn->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_voicemail ' .
            'WHERE vcc_id = :vcc_id ' . $where,
            $params
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_voicemail', $addInfo);
        $list = $conn->fetchAll(
            "SELECT id,caller,called,start_time,rec_secs,rec_file,listen_mark,down_mark " .
            "FROM win_voicemail " .
            "WHERE vcc_id = :vcc_id " . $where .
            'ORDER BY ' . $page['sort'] . ' ' . $page['order'] . ' LIMIT ' . $page['start'] . ',' . $page['limit'],
            $params
        );
        $result = array();
        foreach ($list as $k => $v) {
            $result[$k] = $v;
            $result[$k]['start_time'] = date("Y-m-d H:i:s", $v['start_time']);
            //$result[$k]['rec_file'] = "./includes/cls_download.php?type=url&filename=http://$win_ip:$win_web_port/$win_system_name/cls_download.php?filename=" . $v['rec_file'];
            $result[$k]['listen_mark'] = $v['listen_mark'] == 1 ? "已收听" : "未收听";
            $result[$k]['down_mark'] = $v['down_mark'] == 1 ? "已下载" : "未下载";
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
        );
        return new JsonResponse($ret);
    }

    /**
     * 收听留言接口
     * @param Request $request
     * @return JsonResponse|Response
     */
    public function playVoiceAction(Request $request)
    {
        $filename = $request->get("filename");
        if (empty($filename) || !file_exists($filename)) {
            $ret = array(
                'code' => 401,
                'message' => '留言地址为空或文件不存在',
            );
            return new JsonResponse($ret);
        }

        //$record_url = $this->container->getParameter('record_url');
        //$remoteFile = $record_url.$filename;
        //$remoteFileSize = $this->getRemoteFileSize($remoteFile);
        $fileType = $this->get('help.function')->getSoundFileType($filename);
        return new Response(file_get_contents($filename), 200, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => filesize($filename),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($filename)
        ));
    }

    /**
     * 获取远程文件大小
     *
     * @param $remoteFile
     * @return bool|int|string
     */
    public function getRemoteFileSize($remoteFile)
    {
        $headers = get_headers($remoteFile);
        $remoteFileSize = 0;
        foreach ($headers as $header) {
            $headerString = explode(':', $header);
            if ($headerString[0] == 'Content-Length') {
                $remoteFileSize = $headerString[1];
                break;
            }
        }

        return $remoteFileSize;
    }

    /**
     * @param $vcc_id
     * @param $call_id
     * @return JsonResponse|Response
     */
    public function voiceAction($vcc_id, $call_id)
    {
        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($call_id)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );
            return new JsonResponse($ret);
        }
        /*if (!is_numeric($call_id)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id格式不对，要求为数字',
            );
            return new JsonResponse($ret);
        }*/

        /** @var \Doctrine\DBAL\Connection $conn*/
        $conn = $this->get('doctrine.dbal.default_connection');
        $where = "vcc_id=:vcc_id AND call_id=:call_id";
        $param = array('vcc_id'=>$vcc_id,'call_id'=>$call_id);
        $recordFile = $conn->fetchColumn(
            'SELECT rec_file FROM win_voicemail
            WHERE '.$where.' LIMIT 1',
            $param
        );

        if (empty($recordFile) || !file_exists($recordFile)) {
            $ret = array(
                'code' => 405,
                'message' => '录音文件不存在',
            );
            return new JsonResponse($ret);
        }

//        $record_url = $this->container->getParameter('record_url');
//        $remoteFile = $record_url.$recordFile;
//        $remoteFileSize = $this->getRemoteFileSize($remoteFile);
        $fileType = $this->get('help.function')->getSoundFileType($recordFile);
        return new Response(file_get_contents($recordFile), 200, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => filesize($recordFile),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile)
        ));
    }
}
